package study.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import study.models.DatabaseManagement;
import study.models.Image;

/**
 * Servlet implementation class Authentication
 */

public class Authentication extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public Authentication() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		PrintWriter writer = response.getWriter();

		DatabaseManagement dbms = new DatabaseManagement();
		if (dbms.checkUser(username, password)) {
			
			Cookie cookie = new Cookie("location", "TP HCM");
			response.addCookie(cookie);
			HttpSession session = request.getSession();
			session.setMaxInactiveInterval(15);
			session.setAttribute("username", username);
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/imageshow");
			Image image = new Image("haha", 200, 300);
			request.setAttribute("Angry Bird", image);
			
			session.setAttribute("Testing image", new Image("testing", 200, 300));
			session.removeAttribute("Testing image");
			dispatcher.forward(request, response);
		} else {
			response.sendRedirect("Login.jsp");
		}

	}

}
